<template>
    <MatchGround v-if="gameStore.status === 'matching'" :game-invitation="gameInvitation" />
    <PlayGround v-if="gameStore.status === 'playing'" />
    <ResultBoard v-if="gameStore.loser !== 'none'" />
</template>

<script>
import { onMounted, onUnmounted, onBeforeUnmount, ref } from 'vue'
import { useUserStore } from '@/store/user'
import { useGameStore } from '@/store/game'
import MatchGround from '@/views/game/MatchGround.vue'
import PlayGround from '@/views/game/pk/mul/PlayGround.vue'
import ResultBoard from '@/views/game/ResultBoard.vue'
import { ElNotification } from 'element-plus'

export default {
    components: {
        MatchGround,
        PlayGround,
        ResultBoard,
    },
    setup() {
        const gameStore = useGameStore()
        const userStore = useUserStore()
        const socketUrl = `wss://www.xujiaojiaojiao.cn/websocket/${userStore.token}`
        let socket = null
        let gameMapInstance = null

        // 游戏邀请相关状态
        const gameInvitation = ref(null)

        // 添加退订游戏的方法
        const unsubscribeGame = () => {
            // 如果socket连接有效且不在matching状态，发送游戏结束通知
            if (socket && socket.readyState === WebSocket.OPEN && gameStore.status !== 'matching') {
                const endGameEvent = {
                    event: 'end-game',
                }
                socket.send(JSON.stringify(endGameEvent))
            }

            // 使用resetGame方法完全重置游戏状态
            gameStore.resetGame()
        }

        onMounted(() => {
            // 设置显示邀请弹窗
            gameStore.showInvitation = true

            // 不需要预先设置默认对手信息，因为服务器会发送真实信息
            socket = new WebSocket(socketUrl)
            socket.onopen = () => {
                gameStore.updateSocket(socket)
            }
            socket.onmessage = (msg) => {
                try {
                    const data = JSON.parse(msg.data)

                    // 改为从gameStore获取已存在的实例
                    if (!gameMapInstance && gameStore.gameObject) {
                        gameMapInstance = gameStore.gameObject
                    }

                    switch (data.event) {
                        case 'start-matching':
                            gameStore.updateOpponents({
                                player1: {
                                    id: data.opponent1_id,
                                    username: data.opponent1_username,
                                    photo: data.opponent1_photo,
                                },
                                player2: {
                                    id: data.opponent2_id,
                                    username: data.opponent2_username,
                                    photo: data.opponent2_photo,
                                },
                            })

                            // 设置游戏中各个玩家的ID映射
                            gameStore.updateGame({
                                a_id: data.game.a_id,
                                b_id: data.game.b_id,
                                c_id: data.game.c_id,
                            })

                            setTimeout(() => {
                                gameStore.updateStatus('playing')
                            }, 2000)
                            break
                        case 'move':
                            // 确保gameMapInstance有效
                            if (!gameMapInstance && gameStore.gameObject) {
                                gameMapInstance = gameStore.gameObject
                            }

                            if (gameMapInstance) {
                                if (gameMapInstance._destroyed) {
                                    console.warn('GameMap已被销毁，但仍在接收移动消息，尝试恢复...')
                                    if (gameStore.gameObject && !gameStore.gameObject._destroyed) {
                                        gameMapInstance = gameStore.gameObject
                                    } else {
                                        console.error('无法获取有效的GameMap实例，忽略移动消息')
                                        break
                                    }
                                }

                                // 调用处理移动的方法
                                gameMapInstance.handlePlayerMove(data)
                            } else {
                                console.error('收到移动消息，但gameMapInstance不存在')
                            }
                            break
                        case 'shoot-fireball':
                            // 确保gameMapInstance有效
                            if (!gameMapInstance && gameStore.gameObject) {
                                gameMapInstance = gameStore.gameObject
                            }

                            if (gameMapInstance && !gameMapInstance._destroyed) {
                                gameMapInstance.handlePlayerShootFireball(data)
                            }
                            break
                        case 'heal':
                            // 确保gameMapInstance有效
                            if (!gameMapInstance && gameStore.gameObject) {
                                gameMapInstance = gameStore.gameObject
                            }

                            if (gameMapInstance && !gameMapInstance._destroyed) {
                                gameMapInstance.handle_player_heal(data)
                            }
                            break
                        case 'flash':
                            if (!gameMapInstance && gameStore.gameObject) {
                                gameMapInstance = gameStore.gameObject
                            }

                            if (gameMapInstance && !gameMapInstance._destroyed) {
                                gameMapInstance.handle_player_flash(data)
                            }
                            break
                        case 'heal-cooldown':
                            // 确保gameMapInstance有效
                            if (!gameMapInstance && gameStore.gameObject) {
                                gameMapInstance = gameStore.gameObject
                            }

                            if (gameMapInstance && !gameMapInstance._destroyed) {
                                gameMapInstance.handle_heal_cooldown(data)
                            }
                            break
                        case 'fireball-hit':
                            // 确保gameMapInstance有效
                            if (!gameMapInstance && gameStore.gameObject) {
                                gameMapInstance = gameStore.gameObject
                            }

                            if (gameMapInstance && !gameMapInstance._destroyed) {
                                const player = gameMapInstance.players.find(
                                    (p) => p.info.userId === data.playerId
                                )
                                if (player) {
                                    player.handleHitEvent(data)
                                } else {
                                    console.error(`无法找到被击中的玩家 ID=${data.playerId}`)
                                }
                            }
                            break
                        case 'result': {
                            // 防止覆盖已经确定的结果（比如已经确定某人胜利后又收到平局）
                            const currentLoser = gameStore.loser
                            if (currentLoser !== 'none' && data.loser === 'all') {
                                console.log('忽略平局结果，因为已经确定了胜负:', currentLoser)
                            } else {
                                gameStore.updateLoser(data.loser)
                            }
                            break
                        }
                        case 'player_death': {
                            // 处理玩家死亡事件，确保在所有客户端上同步移除玩家
                            gameStore.handlePlayerDeath(data.player_id)

                            // 确保游戏对象和玩家数组存在且游戏未结束
                            if (!gameMapInstance && gameStore.gameObject) {
                                gameMapInstance = gameStore.gameObject
                            }

                            if (
                                gameMapInstance &&
                                !gameMapInstance._destroyed &&
                                gameStore.loser === 'none'
                            ) {
                                // 查找死亡的玩家
                                const player = gameMapInstance.players.find(
                                    (p) =>
                                        p.info &&
                                        p.info.userId == data.player_id &&
                                        !p.is_dead &&
                                        p.info.hp > 0
                                )

                                if (player) {
                                    // 标记为死亡状态
                                    player.info.hp = 0
                                    player.is_dead = true

                                    // 调用Player类的set_death方法
                                    if (typeof player.set_death === 'function') {
                                        try {
                                            player.set_death()
                                        } catch (e) {
                                            console.warn(`调用set_death方法失败:`, e)
                                        }
                                    }
                                } else {
                                    console.warn(
                                        `找不到活跃状态下ID为 ${data.player_id} 的玩家，可能已处理过死亡事件`
                                    )
                                }
                            }
                            break
                        }
                        case 'game-invite':
                            // 在匹配页面收到游戏邀请时，设置邀请信息
                            gameInvitation.value = {
                                fromUserId: data.fromUserId,
                                username: data.fromUsername,
                                photo: data.fromUserPhoto,
                            }
                            break

                        case 'game-invite-result':
                            // 处理游戏邀请响应
                            // 如果当前在匹配页面，更新匹配按钮状态
                            if (gameStore.status === 'matching') {
                                if (data.response === 'accept') {
                                    // 如果对方接受了邀请，更新匹配按钮状态
                                    const matchBtn = document.querySelector('.match-btn')
                                    if (matchBtn) {
                                        matchBtn.textContent = '取消'
                                    }

                                    // 显示接受邀请的提示
                                    ElNotification({
                                        title: '游戏邀请已接受',
                                        message: `${data.fromUsername} 接受了您的游戏邀请`,
                                        type: 'success',
                                        duration: 3000,
                                    })
                                } else {
                                    // 如果对方拒绝了邀请，更新匹配按钮状态
                                    const matchBtn = document.querySelector('.match-btn')
                                    if (matchBtn) {
                                        matchBtn.textContent = '开始匹配'
                                    }

                                    // 显示拒绝邀请的提示
                                    ElNotification({
                                        title: '游戏邀请被拒绝',
                                        message: `${data.fromUsername} 拒绝了您的游戏邀请`,
                                        type: 'error',
                                        duration: 3000,
                                    })
                                }
                            }
                            break
                    }
                } catch (error) {
                    console.error('处理WebSocket消息时出错:', error)
                }
            }

            socket.onclose = () => {
                gameStore.updateStatus('matching') // 将关闭状态设置为匹配中
            }
            socket.onerror = (error) => {
                console.error('WebSocket 连接出错:', error)
            }
        })

        // 在组件卸载前发送游戏结束通知
        onBeforeUnmount(() => {
            // 不显示邀请弹窗
            gameStore.showInvitation = false
            unsubscribeGame()
        })

        onUnmounted(() => {
            // 先发送游戏结束通知
            if (
                socket &&
                (socket.readyState === WebSocket.OPEN ||
                    socket.readyState === WebSocket.CONNECTING) &&
                gameStore.status === 'playing'
            ) {
                try {
                    // 明确发送end-game事件
                    const endGameEvent = {
                        event: 'end-game',
                        userId: userStore.id,
                    }
                    socket.send(JSON.stringify(endGameEvent))

                    // 等待一小段时间确保消息发送成功
                    setTimeout(() => {
                        try {
                            unsubscribeGame()
                        } catch (e) {
                            console.error('延迟取消游戏订阅出错:', e)
                        }
                    }, 300)
                } catch (e) {
                    console.error('发送游戏结束事件出错:', e)
                    unsubscribeGame()
                }
            } else {
                unsubscribeGame()
            }

            if (socket) {
                // 增加状态检查防止重复关闭
                if (
                    socket.readyState === WebSocket.OPEN ||
                    socket.readyState === WebSocket.CONNECTING
                ) {
                    try {
                        socket.close()
                    } catch (e) {
                        console.error('关闭WebSocket连接时出错:', e)
                    }
                }
                socket = null
            }

            // 新增游戏实例清理
            if (gameMapInstance) {
                try {
                    if (typeof gameMapInstance.destroy === 'function') {
                        gameMapInstance.destroy()
                    }
                    gameMapInstance = null
                } catch (e) {
                    console.error('销毁GameMap实例时出错:', e)
                    gameMapInstance = null
                }
            }
        })

        return {
            gameStore,
            gameInvitation,
        }
    },
}
</script>
